package com.example.myapplication.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.example.myapplication.R
import com.example.myapplication.databinding.ActivityLoginBinding
import com.example.myapplication.utils.GsonUtils
import com.example.myapplication.utils.NetUtils
import com.google.gson.Gson
import okhttp3.FormBody

class LoginActivity : AppCompatActivity() {
    lateinit var binding: ActivityLoginBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        val sharedPreferences =
            binding.root.context.getSharedPreferences("Chihiro", Context.MODE_PRIVATE)
        if (!sharedPreferences.getBoolean("SplashState", false)) {
            val intent = Intent(this, SplashActivity::class.java)
            startActivity(intent)
        }
        binding.titleBar.internetTextView.setOnClickListener {
            val intent = Intent(this, InternetActivity::class.java)
            startActivity(intent)
        }
        binding.button.setOnClickListener {
            login()
        }

    }

    fun login() {
        val userName = binding.usernameEditText.text.toString()
        val password = binding.passwordEditText.text.toString()
        if (userName.isEmpty() || password.isEmpty()) {
            Toast.makeText(binding.root.context, "用户名或密码不能为空", Toast.LENGTH_SHORT).show()
        } else {
            val requestBody =
                FormBody.Builder().add("userName", userName).add("password", password).build()
            NetUtils.post("user/login", null, requestBody, Handler {
                val data = GsonUtils.jsonObject(it.obj as String)
                Log.d("TAG", "login: ${data.get("msg")}")
                if (data.get("msg").toString() == "\"操作失败\"") {
                    Toast.makeText(binding.root.context, "用户名或密码错误", Toast.LENGTH_SHORT)
                        .show()
                } else {
                    val intent = Intent(this, IndexActivity::class.java)
                    startActivity(intent)
                }
                false
            })

        }
    }
}